package com.ngc.mall.controller;

import com.ngc.mall.common.configure.response.ResponseResult;
import com.ngc.mall.param.TokenParam;
import com.ngc.mall.service.IWxAuthenticationService;
import com.ngc.mall.util.JwtToken;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
@RequestMapping("/wechat")
public class TokenController {
    /**
     * 获取token
     * @param code
     * @return
     */
    @Resource
    IWxAuthenticationService wxAuthenticationService;


    @GetMapping("/token/{code}")
    public ResponseResult<String> getToken(@PathVariable String code){
        String token=null;
        token=wxAuthenticationService.code2Session(code);
        System.out.println(token);
        return ResponseResult.success(token);
    }

    /**
     * 判断token是否过期
     * (用于小程序进入页面判断token是否过期，调用业务请求时以header传递）
     * @param token
     * @return
     */
    @PostMapping("/token/verify")
    public ResponseResult<Boolean> verifyToken(@RequestBody TokenParam token){
        Boolean valid = JwtToken.verifyToken(token.getToken());
        System.out.println(valid);
        return ResponseResult.success(valid);
    }

    @GetMapping("/wx")
    public void checkSignature(HttpServletResponse response, HttpServletRequest request) throws IOException {
          /*参数	描述
            signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
            timestamp	时间戳
            nonce	    随机数
            echostr	    随机字符串
        */
        //获取参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        System.out.printf(signature,timestamp,nonce,echostr);
        //校验消息是否来自微信服务器
        PrintWriter out =response.getWriter();

    }
}
